package com.sina.finance.api.sdk;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public abstract class WebUtils {
    private static boolean ignoreSSLCheck = true;
    public static final String DEFAULT_CHARSET = "UTF-8";
    private static final String METHOD_POST = "POST";
    private static final String METHOD_GET = "GET";

    public static String doPost(String url, Map<String, String> postDatas, int connectTimeout, int readTimeout) {
        return doPost(url, postDatas, "UTF-8", connectTimeout, readTimeout);
    }

    public static String doPost(String url, Map<String, String> paramMap, String charset, int connectTimeout, int readTimeout) {
        String contentType = new StringBuilder().append("application/x-www-form-urlencoded;charset=").append(charset).toString();
        String str2 = buildQuery(paramMap, charset);
        byte[] stream = new byte[0];
        if (str2 != null) {
            try {
                stream = str2.getBytes(charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return doPost(url, contentType, stream, connectTimeout, readTimeout);
    }

    public static String doPost(String url, String contentType, byte[] paramArrayOfByte, int connectTimeout, int readTimeout) {
        HttpURLConnection localHttpURLConnection = null;
        OutputStream localOutputStream = null;
        String str = null;
        try {
            Map localMap;
            try {
                localHttpURLConnection = getConnection(new URL(url), "POST", contentType);
                localHttpURLConnection.setConnectTimeout(connectTimeout);
                localHttpURLConnection.setReadTimeout(readTimeout);
            } catch (IOException ioE) {
                localMap = getParamsFromUrl(url);
                ApiLogger.logCommError(ioE, url, (String) localMap.get("app_key"), (String) localMap.get("method"), paramArrayOfByte);
                throw new RuntimeException(ioE);
            }
            try {
                localOutputStream = localHttpURLConnection.getOutputStream();
                localOutputStream.write(paramArrayOfByte);
                str = getResponseAsString(localHttpURLConnection);
            } catch (IOException ioE) {
                localMap = getParamsFromUrl(url);
                ApiLogger.logCommError(ioE, localHttpURLConnection, (String) localMap.get("app_key"), (String) localMap.get("method"), paramArrayOfByte);
                throw new RuntimeException(ioE);
            }
        } finally {
            if (localOutputStream != null) {
                try {
                    localOutputStream.close();
                } catch (IOException ioE) {
                    throw new RuntimeException(ioE);
                }
            }
            if (localHttpURLConnection != null) {
                localHttpURLConnection.disconnect();
            }
        }

        return str;
    }


    private static byte[] getTextEntry(String paramString1, String paramString2, String paramString3) throws IOException {
        StringBuilder localStringBuilder = new StringBuilder();
        localStringBuilder.append("Content-Disposition:form-data;name=\"");
        localStringBuilder.append(paramString1);
        localStringBuilder.append("\"\r\nContent-Type:text/plain\r\n\r\n");
        localStringBuilder.append(paramString2);
        return localStringBuilder.toString().getBytes(paramString3);
    }

    private static byte[] getFileEntry(String paramString1, String paramString2, String paramString3, String paramString4) throws IOException {
        StringBuilder localStringBuilder = new StringBuilder();
        localStringBuilder.append("Content-Disposition:form-data;name=\"");
        localStringBuilder.append(paramString1);
        localStringBuilder.append("\";filename=\"");
        localStringBuilder.append(paramString2);
        localStringBuilder.append("\"\r\nContent-Type:");
        localStringBuilder.append(paramString3);
        localStringBuilder.append("\r\n\r\n");
        return localStringBuilder.toString().getBytes(paramString4);
    }

    private static byte[] getCosFileEntry(String paramString1, String paramString2, String paramString3, String paramString4) throws IOException {
        StringBuilder localStringBuilder = new StringBuilder();
        localStringBuilder.append("Content-Disposition:form-data;name=\"");
        localStringBuilder.append(paramString1);
        localStringBuilder.append("\";filename=\"");
        localStringBuilder.append(paramString2);
        localStringBuilder.append("\"\r\nContent-Type:");
        localStringBuilder.append(paramString3);
        localStringBuilder.append("\r\n\r\n");
        return localStringBuilder.toString().getBytes(paramString4);
    }

    public static String doGet(String paramString, Map<String, String> paramMap)
            throws IOException {
        return doGet(paramString, paramMap, "UTF-8");
    }

    public static String doGet(String paramString1, Map<String, String> paramMap, String paramString2)
            throws IOException {
        HttpURLConnection localHttpURLConnection = null;
        String str1 = null;
        try {
            String str2 = new StringBuilder().append("application/x-www-form-urlencoded;charset=").append(paramString2).toString();
            String str3 = buildQuery(paramMap, paramString2);
            Map localMap;
            try {
                localHttpURLConnection = getConnection(buildGetUrl(paramString1, str3), "GET", str2);
            } catch (IOException localIOException1) {
                localMap = getParamsFromUrl(paramString1);
                ApiLogger.logCommError(localIOException1, paramString1, (String) localMap.get("app_key"), (String) localMap.get("method"), paramMap);
                throw localIOException1;
            }
            try {
                str1 = getResponseAsString(localHttpURLConnection);
            } catch (IOException localIOException2) {
                localMap = getParamsFromUrl(paramString1);
                ApiLogger.logCommError(localIOException2, localHttpURLConnection, (String) localMap.get("app_key"), (String) localMap.get("method"), paramMap);
                throw localIOException2;
            }
        } finally {
            if (localHttpURLConnection != null) {
                localHttpURLConnection.disconnect();
            }
        }

        return str1;
    }

    private static HttpURLConnection getConnection(URL url, String methodType, String contentType) throws IOException {
        HttpURLConnection localObject = (HttpURLConnection) url.openConnection();
        if ((localObject instanceof HttpsURLConnection)) {
            HttpsURLConnection localHttpsURLConnection = (HttpsURLConnection) localObject;
            if (ignoreSSLCheck) {
                try {
                    SSLContext localSSLContext = SSLContext.getInstance("TLS");
                    localSSLContext.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
                    localHttpsURLConnection.setSSLSocketFactory(localSSLContext.getSocketFactory());
                    localHttpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String paramAnonymousString, SSLSession paramAnonymousSSLSession) {
                            return true;
                        }
                    });
                } catch (Exception localException) {
                    throw new IOException(localException);
                }

            }

            localObject = localHttpsURLConnection;
        }

        ((HttpURLConnection) localObject).setRequestMethod(methodType);
        ((HttpURLConnection) localObject).setDoInput(true);
        ((HttpURLConnection) localObject).setDoOutput(true);
        ((HttpURLConnection) localObject).setRequestProperty("Accept", "text/xml,text/javascript,text/html");
        ((HttpURLConnection) localObject).setRequestProperty("User-Agent", "rop-sdk-java");
        ((HttpURLConnection) localObject).setRequestProperty("Content-Type", contentType);
        return localObject;
    }

    private static URL buildGetUrl(String paramString1, String paramString2) throws IOException {
        URL localURL = new URL(paramString1);
        if (StringUtils.isEmpty(paramString2)) {
            return localURL;
        }

        if (StringUtils.isEmpty(localURL.getQuery())) {
            if (paramString1.endsWith("?"))
                paramString1 = new StringBuilder().append(paramString1).append(paramString2).toString();
            else {
                paramString1 = new StringBuilder().append(paramString1).append("?").append(paramString2).toString();
            }
        } else if (paramString1.endsWith("&"))
            paramString1 = new StringBuilder().append(paramString1).append(paramString2).toString();
        else {
            paramString1 = new StringBuilder().append(paramString1).append("&").append(paramString2).toString();
        }

        return new URL(paramString1);
    }

    public static String buildQuery(Map<String, String> paramMap, String paramString) {
        if ((paramMap == null) || (paramMap.isEmpty())) {
            return null;
        }

        StringBuilder localStringBuilder = new StringBuilder();
        Set<Map.Entry<String, String>> entries = paramMap.entrySet();
        int i = 0;

        for (Map.Entry localEntry : entries) {
            String str1 = (String) localEntry.getKey();
            String str2 = (String) localEntry.getValue();

            if (StringUtils.areNotEmpty(new String[]{str1, str2})) {
                if (i != 0)
                    localStringBuilder.append("&");
                else {
                    i = 1;
                }

                try {
                    localStringBuilder.append(str1).append("=").append(URLEncoder.encode(str2, paramString));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("url coding fail:", e);
                }
            }
        }

        return localStringBuilder.toString();
    }

    protected static String getResponseAsString(HttpURLConnection paramHttpURLConnection) throws IOException {
        String str1 = getResponseCharset(paramHttpURLConnection.getContentType());
        InputStream localInputStream = paramHttpURLConnection.getErrorStream();
        if (localInputStream == null) {
            return getStreamAsString(paramHttpURLConnection.getInputStream(), str1);
        }
        String str2 = getStreamAsString(localInputStream, str1);
        if (StringUtils.isEmpty(str2)) {
            throw new IOException(new StringBuilder().append(paramHttpURLConnection.getResponseCode()).append(":").append(paramHttpURLConnection.getResponseMessage()).toString());
        }
        throw new IOException(str2);
    }

    private static String getStreamAsString(InputStream paramInputStream, String paramString) throws IOException {
        try {
            BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(paramInputStream, paramString));
            StringWriter localStringWriter = new StringWriter();

            char[] arrayOfChar = new char[''];
            int i = 0;
            while ((i = localBufferedReader.read(arrayOfChar)) > 0) {
                localStringWriter.write(arrayOfChar, 0, i);
            }

            return localStringWriter.toString();
        } finally {
            if (paramInputStream != null)
                paramInputStream.close();
        }
    }

    private static String getResponseCharset(String paramString) {
        String str1 = "UTF-8";

        if (!StringUtils.isEmpty(paramString)) {
            String[] arrayOfString1 = paramString.split(";");
            for (String str2 : arrayOfString1) {
                str2 = str2.trim();
                if (str2.startsWith("charset")) {
                    String[] arrayOfString3 = str2.split("=", 2);
                    if ((arrayOfString3.length != 2) ||
                            (StringUtils.isEmpty(arrayOfString3[1]))) break;
                    str1 = arrayOfString3[1].trim();
                    break;
                }

            }

        }

        return str1;
    }

    public static String decode(String paramString) {
        return decode(paramString, "UTF-8");
    }

    public static String encode(String paramString) {
        return encode(paramString, "UTF-8");
    }

    public static String decode(String paramString1, String paramString2) {
        String str = null;
        if (!StringUtils.isEmpty(paramString1)) {
            try {
                str = URLDecoder.decode(paramString1, paramString2);
            } catch (IOException localIOException) {
                throw new RuntimeException(localIOException);
            }
        }
        return str;
    }

    public static String encode(String paramString1, String paramString2) {
        String str = null;
        if (!StringUtils.isEmpty(paramString1)) {
            try {
                str = URLEncoder.encode(paramString1, paramString2);
            } catch (IOException localIOException) {
                throw new RuntimeException(localIOException);
            }
        }
        return str;
    }

    private static Map<String, String> getParamsFromUrl(String paramString) {
        Map<String, String> localObject = null;
        if ((paramString != null) && (paramString.indexOf(63) != -1)) {
            localObject = splitUrlQuery(paramString.substring(paramString.indexOf(63) + 1));
        }
        if (localObject == null) {
            localObject = new HashMap();
        }
        return localObject;
    }

    public static Map<String, String> splitUrlQuery(String paramString) {
        HashMap localHashMap = new HashMap();

        String[] arrayOfString1 = paramString.split("&");
        if ((arrayOfString1 != null) && (arrayOfString1.length > 0)) {
            for (String str : arrayOfString1) {
                String[] arrayOfString3 = str.split("=", 2);
                if ((arrayOfString3 != null) && (arrayOfString3.length == 2)) {
                    localHashMap.put(arrayOfString3[0], arrayOfString3[1]);
                }
            }
        }

        return localHashMap;
    }

    private static class TrustAllTrustManager
            implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }
    }
}

